/* eslint-disable @typescript-eslint/no-non-null-assertion */
import { useRef } from 'react';

function usePersistFn<T extends (...args: any[]) => any>(fn: T): T {
	const fnRef = useRef<T>(fn);
	fnRef.current = fn;

	const persistFn = useRef<T>();
	if (!persistFn.current) {
		persistFn.current = function (...args) {
			// eslint-disable-next-line @typescript-eslint/ban-ts-comment
			// @ts-ignore
			return fnRef.current!.apply(this, args);
		} as T;
	}

	return persistFn.current!;
}

export default usePersistFn;
